<template>
  <div class="manage-container">
    <div class="page-header">
      <h2>展演管理</h2>
      <el-button type="primary" @click="exportRegistrationList(searchForm)" :disabled="!tableData.length">导出列表</el-button>
    </div>
    <div class="page-content">
      <!-- 搜索表单 -->
      <el-form :inline="true" class="search-form">
        <el-form-item label="机构">
          <el-select 
            v-model="searchForm.organizationId" 
            placeholder="请选择机构" 
            clearable
            :disabled="organizationOptions.length === 1"
          >
            <el-option
              v-for="org in organizationOptions"
              :key="org.id"
              :label="org.username"
              :value="org.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="活动名称">
          <el-input v-model="searchForm.activityName" placeholder="请输入活动名称" clearable />
        </el-form-item>
        <el-form-item label="报名姓名">
          <el-input v-model="searchForm.registrantName" placeholder="请输入报名姓名" clearable />
        </el-form-item>
        <el-form-item label="活动状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="进行中" value="ongoing" />
            <el-option label="已结束" value="ended" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格容器 -->
      <div class="table-container">
        <el-table 
          :data="tableData" 
          border 
          style="width: 100%"
          height="600px"
        >
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="name" label="姓名" min-width="100" />
          <el-table-column prop="gender" label="性别" width="80" />
          <el-table-column prop="performanceGroup" label="展演组别/所在年级" min-width="150" />
          <el-table-column prop="workTitle" label="作品名称" min-width="150" />
          <el-table-column prop="performersCount" label="表演人数" width="100" align="center" />
          <el-table-column prop="backgroundMaterial" label="背景素材音视频" min-width="120" />
          <el-table-column prop="makeupService" label="是否需要化妆服务" width="140">
            <template #default="scope">
              {{ scope.row.makeupService ? '需要' : '不需要' }}
            </template>
          </el-table-column>
          <el-table-column prop="campus" label="所在校区" min-width="120" />
          <el-table-column label="操作" width="230" fixed="right">
            <template #default="scope">
              <div class="text-center">
                <el-button type="primary" @click="handleView(scope.row)">查看</el-button>
                <el-button type="primary" @click="handleEdit(scope.row)">编辑</el-button>
                <el-button type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 查看详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="报名详情"
      width="1000px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="ID">{{ currentRegistration?.id }}</el-descriptions-item>
        <el-descriptions-item label="报名时间">{{ formatDateTime(currentRegistration?.createdAt) }}</el-descriptions-item>
        
        <el-descriptions-item label="姓名">{{ currentRegistration?.name }}</el-descriptions-item>
        <el-descriptions-item label="性别">{{ currentRegistration?.gender }}</el-descriptions-item>
        
        <el-descriptions-item label="证件类型">{{ currentRegistration?.idType }}</el-descriptions-item>
        <el-descriptions-item label="证件号码">{{ currentRegistration?.idNumber }}</el-descriptions-item>
        
        <el-descriptions-item label="出生日期">{{ currentRegistration?.birthDate }}</el-descriptions-item>
        <el-descriptions-item label="所在校区">{{ currentRegistration?.campus }}</el-descriptions-item>
        
        <el-descriptions-item label="展演组别/所在年级">{{ currentRegistration?.performanceGroup }}</el-descriptions-item>
        <el-descriptions-item label="作品名称">{{ currentRegistration?.workTitle }}</el-descriptions-item>
        
        <el-descriptions-item label="表演人数">{{ currentRegistration?.performersCount }}</el-descriptions-item>
        <el-descriptions-item label="是否需要化妆服务">{{ currentRegistration?.makeupService ? '需要' : '不需要' }}</el-descriptions-item>
        
        <el-descriptions-item label="陪同家长姓名">{{ currentRegistration?.parentName }}</el-descriptions-item>
        <el-descriptions-item label="陪同家长电话">{{ currentRegistration?.parentPhone }}</el-descriptions-item>
        
        <el-descriptions-item label="指导老师">{{ currentRegistration?.teacherName }}</el-descriptions-item>
        <el-descriptions-item label="指导老师电话">{{ currentRegistration?.teacherPhone }}</el-descriptions-item>
        
        <el-descriptions-item label="报名活动">{{ currentRegistration?.activity?.name }}</el-descriptions-item>
        <el-descriptions-item label="活动时间">{{ formatDateTime(currentRegistration?.activity?.performanceTime) }}</el-descriptions-item>
        
        <el-descriptions-item label="活动地点" :span="2">{{ formatAddress(currentRegistration?.activity) }}</el-descriptions-item>
        
        <el-descriptions-item label="背景素材音视频" :span="2">{{ currentRegistration?.backgroundMaterial }}</el-descriptions-item>
        
        <el-descriptions-item label="备注" :span="2">{{ currentRegistration?.remarks || '无' }}</el-descriptions-item>
      </el-descriptions>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑报名信息"
      width="1000px"
    >
      <el-form :model="editForm" label-width="140px" :rules="rules" ref="editFormRef">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="editForm.name" class="custom-input"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="editForm.gender" class="custom-input">
                <el-option label="男" value="男" />
                <el-option label="女" value="女" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="证件类型" prop="idType">
              <el-select v-model="editForm.idType" class="custom-input">
                <el-option label="身份证" value="身份证" />
                <el-option label="护照" value="护照" />
                <el-option label="港澳通行证" value="港澳通行证" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="证件号码" prop="idNumber">
              <el-input v-model="editForm.idNumber" maxlength="18" class="custom-input"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出生日期" prop="birthDate">
              <el-date-picker
                v-model="editForm.birthDate"
                type="date"
                class="custom-input"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="展演组别/所在年级" prop="performanceGroup">
              <el-select v-model="editForm.performanceGroup" class="custom-input">
                <el-option
                  v-for="group in performanceGroups"
                  :key="group.id"
                  :label="group.name"
                  :value="group.name"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="作品名称" prop="workTitle">
              <el-input v-model="editForm.workTitle" class="custom-input"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="表演人数" prop="performersCount">
              <el-input-number v-model="editForm.performersCount" :min="1" class="custom-input"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="背景素材音视频" prop="backgroundMaterial">
              <el-select v-model="editForm.backgroundMaterial" class="custom-input">
                <el-option
                  v-for="type in backgroundMaterialTypes"
                  :key="type.id"
                  :label="type.name"
                  :value="type.name"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在校区" prop="campus">
              <el-select v-model="editForm.campus" class="custom-input">
                <el-option
                  v-for="campus in currentCampuses"
                  :key="campus.id"
                  :label="campus.name"
                  :value="campus.name"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否需要化妆服务" prop="makeupService">
              <el-select v-model="editForm.makeupService" class="custom-input">
                <el-option :label="'需要'" :value="true" />
                <el-option :label="'不需要'" :value="false" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="陪同家长姓名" prop="parentName">
              <el-input v-model="editForm.parentName" class="custom-input"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="陪同家长电话" prop="parentPhone">
              <el-input v-model="editForm.parentPhone" maxlength="11" class="custom-input"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="指导老师" prop="teacherName">
              <el-input v-model="editForm.teacherName" class="custom-input"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="指导老师电话" prop="teacherPhone">
              <el-input v-model="editForm.teacherPhone" maxlength="11" class="custom-input"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remarks">
              <el-input type="textarea" v-model="editForm.remarks" class="custom-input"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveEdit">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import Http from '@/utils/http';
import { deleteRegistration,exportRegistrationList } from '@/utils/Api';
// 机构选项
const organizationOptions = ref([])
const backgroundMaterialTypes = ref([])
const performanceGroups = ref([])
// 搜索表单数据结构
const searchForm = reactive({
  organizationId: '',
  activityName: '',
  registrantName: '',
  status: ''
})

// 表格数据
const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 对话框相关
const detailDialogVisible = ref(false)
const currentRegistration = ref(null)

// 编辑相关
const editDialogVisible = ref(false)
const editFormRef = ref(null)
const editForm = ref({})
const currentCampuses = ref([])

// 表单校验规则
const rules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  idType: [{ required: true, message: '请选择证件类型', trigger: 'change' }],
  idNumber: [{ required: true, message: '请输入证件号码', trigger: 'blur' }],
  birthDate: [{ required: true, message: '请选择出生日期', trigger: 'change' }],
  performanceGroup: [{ required: true, message: '请选择展演组别/所在年级', trigger: 'change' }],
  workTitle: [{ required: true, message: '请输入作品名称', trigger: 'blur' }],
  performersCount: [{ required: true, message: '请输入表演人数', trigger: 'blur' }],
  backgroundMaterial: [{ required: true, message: '请选择背景素材音视频', trigger: 'change' }],
  campus: [{ required: true, message: '请选择所在校区', trigger: 'change' }],
  makeupService: [{ required: true, message: '请选择是否需要化妆服务', trigger: 'change' }],
}

// 页面加载时获取数据
onMounted(() => {
  getOrganizations()
  getActivityList()
})

// 获取机构列表
const getOrganizations = async () => {
  try {
    const res = await Http.get({
      url:'/yp_admin/getSubuser'
    })
    organizationOptions.value = res.data.list || []
    
    if (organizationOptions.value.length === 1) {
      searchForm.organizationId = organizationOptions.value[0].id
      getActivityList()
    }
  } catch (error) {
    console.error('获取机构列表失败:', error)
  }
}

// 获取活动列表
const getActivityList = async () => {
  try {
    const params = {
      ...searchForm,
      page: currentPage.value,
      pageSize: pageSize.value
    }
    
    const res = await Http.get({
      url:'/yp_admin/getActivityRegistrationList',
      params
    })
    if (res.data) {
      tableData.value = res.data.list || []
      backgroundMaterialTypes.value = res.data.backgroundMaterialTypes || []
      performanceGroups.value = res.data.performanceGroups || []
      total.value = res.data.total || 0
    }
  } catch (error) {
    console.error('获取报名列表失败:', error)
    ElMessage.error('获取报名列表失败')
  }
}

// 搜索方法
const handleSearch = () => {
  currentPage.value = 1
  getActivityList()
}


// 重置方法
const resetForm = () => {
  const keepOrganizationId = organizationOptions.value.length === 1 ? searchForm.organizationId : ''
  
  Object.assign(searchForm, {
    organizationId: keepOrganizationId,
    activityName: '',
    registrantName: '',
    status: ''
  })
  
  handleSearch()
}

// 分页方法
const handleSizeChange = (val) => {
  pageSize.value = val
  getActivityList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getActivityList()
}

// 查看详情
const handleView = (row) => {
  currentRegistration.value = row
  detailDialogVisible.value = true
}

// 格式化日期时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 格式化地址
const formatAddress = (activity) => {
  if (!activity) return '';
  const { province, city, district, address } = activity;
  return `${province || ''}${city || ''}${district || ''}${address || ''}`;
}

const handleDelete = (id) => {
 
  ElMessageBox.confirm('确定要删除该报名吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    deleteRegistration(id).then(res => {
      if (res) {
      ElMessage.success('删除成功')
      getActivityList()
    } else {
        ElMessage.error('删除失败')
      }
    })
  })
}

// 编辑方法
const handleEdit = (row) => {
  editForm.value = {
    id: row.id,
    name: row.name,
    gender: row.gender,
    idType: row.idType,
    idNumber: row.idNumber,
    birthDate: row.birthDate,
    performanceGroup: row.performanceGroup,
    workTitle: row.workTitle,
    performersCount: row.performersCount,
    backgroundMaterial: row.backgroundMaterial,
    campus: row.campus,
    makeupService: row.makeupService,
    parentName: row.parentName,
    parentPhone: row.parentPhone,
    teacherName: row.teacherName,
    teacherPhone: row.teacherPhone,
    remarks: row.remarks,
    institutionName:row.institutionName
  }
  currentCampuses.value = row.activity?.campuses || []
  editDialogVisible.value = true
}

// 保存编辑
const handleSaveEdit = () => {
  editFormRef.value?.validate(async (valid) => {
    const performanceGroupId = performanceGroups.value.find(item => item.name === editForm.value.performanceGroup)?.id
    const backgroundMaterialTypeId = backgroundMaterialTypes.value.find(item => item.name === editForm.value.backgroundMaterial)?.id
    if (valid) {
      try {
        const res = await Http.post({
          url: '/yp_admin/editRegistration',
          data: {
            ...editForm.value,
            performanceGroupId,
            backgroundMaterialTypeId
          }
        })
        if (res.code === 200) {
          ElMessage.success('保存成功')
          editDialogVisible.value = false
          getActivityList()
        } else {
          ElMessage.error(res.message || '保存失败')
        }
      } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败')
      }
    }
  })
}
</script>

<style scoped lang="scss">
.manage-container {
  height: 100%;
  padding: 20px;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;

  .page-header {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-shrink: 0;
  }

  .page-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: 0;

    .search-form {
      padding-bottom: 20px;
      flex-shrink: 0;
    }

    .table-container {
      flex: 1;
      min-height: 0;
      
      .el-table {
        height: 100%;
        
        // 使用深度选择器修改表格样式
        :deep(.el-table__inner-wrapper) {
          height: 100%;
        }
        
        :deep(.el-table__header-wrapper) {
          flex-shrink: 0;
        }
        
        :deep(.el-table__body-wrapper) {
          height: calc(100% - 40px);
          overflow-y: auto;
        }
        
        // 固定列样式调整
        :deep(.el-table__fixed-right) {
          height: 100%;
          
          .el-table__fixed-header-wrapper {
            background-color: var(--el-bg-color);
          }
          
          .el-table__fixed-body-wrapper {
            height: calc(100% - 40px);
            overflow-y: auto;
          }
        }
      }
    }

    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
      flex-shrink: 0;
    }
  }

  .program-list {
    margin-top: 20px;
    h3 {
      margin: 10px 0;
      font-size: 16px;
      font-weight: 500;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.area-select {
  display: flex;
  gap: 10px;
  
  .el-select {
    width: 33.33%;
  }
}

.image-upload {
  :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration);
    
    &:hover {
      border-color: var(--el-color-primary);
    }
  }

  .upload-placeholder {
    width: 178px;
    height: 178px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    
    .upload-icon {
      font-size: 28px;
      color: #8c939d;
    }
    
    .upload-text {
      color: #8c939d;
      font-size: 14px;
      margin-top: 8px;
    }
  }

  .image-preview {
    position: relative;
    width: 178px;
    height: 178px;
    
    .preview-image {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    
    .image-preview-mask {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.5);
      display: flex;
      justify-content: center;
      align-items: center;
      opacity: 0;
      transition: var(--el-transition-duration);
      
      .preview-icon {
        font-size: 28px;
        color: #fff;
      }
    }
    
    &:hover .image-preview-mask {
      opacity: 1;
    }
  }
}

.el-button + .el-button {
  margin-left: 4px;  /* 减小按钮之间的间距 */
}

// 添加自定义输入框样式
:deep(.custom-input) {
  width: 100%;
  .el-input__wrapper {
    width: 100%;
  }
}
</style>
